package com.lanou.lenanapp.fragment;


import android.app.Dialog;
import android.app.Fragment;
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;

import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.google.gson.Gson;
import com.lanou.lenanapp.R;
import com.lanou.lenanapp.adapter.JokeFragmentAdapter;
import com.lanou.lenanapp.db.DatabaseHelper;
import com.lanou.lenanapp.entity.greendao.JokeEntity;
import com.lanou.lenanapp.util.Utils;
import com.lanou.lenanapp.view.SwipeRefreshLoadingLayout;
import com.lanou.lenanapp.volley.VolleySingleton;


import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

/**
 * 主页段子
 */
public class JokeFragment extends Fragment implements SwipeRefreshLoadingLayout.OnLoadListener, SwipeRefreshLoadingLayout.OnRefreshListener {

    private RecyclerView jokeRecyclerView;
    private JokeFragmentAdapter adapter;
    private GridLayoutManager manager;
    private Context context;
    private List<JokeEntity> jokes;
    private Dialog dialog;
    //上拉刷新 下拉加载
    private SwipeRefreshLoadingLayout jokeswipeRefreshLoadingLayout;
    private DatabaseHelper helper;//数据库操作对象
    
    VolleySingleton volleySingleton = VolleySingleton.getInstance();

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        this.context = context;
    }


    /**
     * 加载布局文件
     * 初始化recyclerView
     **/
    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

        View v = inflater.inflate(R.layout.activity_fragment_joke, null);

        jokeRecyclerView = (RecyclerView) v.findViewById(R.id.jokeRecyclerView);
        jokeswipeRefreshLoadingLayout = (SwipeRefreshLoadingLayout) v.findViewById(R.id.jokeswipeRefreshLoadingLayout);
        jokeswipeRefreshLoadingLayout.setOnLoadListener(this);
        jokeswipeRefreshLoadingLayout.setOnRefreshListener(this);
        return v;

    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        helper = DatabaseHelper.getHelper();//初始化helper
        manager = new GridLayoutManager(context, 1);
        adapter = new JokeFragmentAdapter(getActivity());
        jokeRecyclerView.setLayoutManager(manager);
        //绑定适配器
        jokeRecyclerView.setAdapter(adapter);

        //查询数据库中所有数据
        List<JokeEntity> jokeEntities = helper.queryAllJoke();
        //判断是否有网络(流量也属于网络 记得检查虚拟机的流量是否关闭) 如果没有 则加载数据库中数据
        boolean lenan = checkNet(getActivity());
        if (lenan){
            initData();//网络拉取数据
        }else if (!lenan){//如果没有网 判断数据库是否有数据
            if (jokeEntities != null && jokeEntities.size() > 0){
                adapter.addData(jokeEntities);
            }else {
                Toast.makeText(getActivity(), "请检查您的网络连接..", Toast.LENGTH_LONG).show();
            }
        }

    }


    /***
     * 判断是否有网络  返回的是boolean类型的
     * **/
    public static boolean checkNet(Context context) {
        try {
            ConnectivityManager connectivity = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
            if (connectivity != null) {
                NetworkInfo info = connectivity.getActiveNetworkInfo();
                Log.i("TAG", "info =" + info);
                if (info != null && info.isConnected()) {
                    if (info.getState() == NetworkInfo.State.CONNECTED) {
                        return true;
                    }
                }
            }
        } catch (Exception e) {
            Log.e("TAG", "exception=" + e.toString());
            return false;
        }
        return false;
    }


    //下拉刷新
    @Override
    public void onRefresh() {
        initData();
    }


    private String time;
    private int t;
    private void initData() {
        dialog = Utils.createloadingDialog(getActivity(), "玩命加载中...");
        dialog.show();
        String url = "http://120.55.151.67/weibofun/weibo_list.php?apiver=10701&category=weibo_jokes&page=0&page_size=30&max_timestamp=-1&latest_viewed_ts=-1&platform=iphone&appver=1.9&buildver=1.9.4&udid=0FD678F7-07AA-4EBF-BB39-EB79EAB40753&sysver=7.0.4";
        JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET, url, null, new Response.Listener<JSONObject>() {
            @Override
            public void onResponse(JSONObject response) {
                dialog.dismiss();
                //数据加载成功后停止加载
                jokeswipeRefreshLoadingLayout.setRefreshing(false);
                if (response != null && response.has("items")) {
                    try {
                        JSONArray fir = response.getJSONArray("items");
                        List<JokeEntity> items = new ArrayList<JokeEntity>();
                        Gson gson = new Gson();
                        for (int i = 0; i < fir.length(); i++) {
                            String str = fir.getString(i);
                            JokeEntity j = gson.fromJson(str, JokeEntity.class);
                            items.add(j);
                        }
                        //保存到数据库中
                        helper.saveJokeList(items);
                        //将数据添加到适配器中
                        adapter.addData(items);
                        time = items.get(15).getUpdate_time();
                        t = Integer.parseInt(time);
                    } catch (JSONException e) {
                        e.printStackTrace();
                    } finally {

                    }
                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                error.printStackTrace();
            }
        });
        volleySingleton.addRequest(request);
    }


    /***
     * 上拉加载
     **/
    @Override
    public void onLoad() {
        LoadContent();
    }

    //定义拼接网址的变量
    int page = 0;
    int tamptimes = 0;
    private void LoadContent() {
        page++;
        tamptimes = tamptimes + 24300;
        t = t - tamptimes;
        String url = "http://120.55.151.67/weibofun/weibo_list.php?apiver=10701&category=weibo_jokes&page=" + page
                + "&page_size=15&max_timestamp=" + t
                + "&latest_viewed_ts=-1&platform=iphone&appver=1.9&buildver=1.9.4&udid=0FD678F7-07AA-4EBF-BB39-EB79EAB40753&sysver=7.0.4";
        JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET, url, null, new Response.Listener<JSONObject>() {
            @Override
            public void onResponse(JSONObject response) {
                jokeswipeRefreshLoadingLayout.setLoading(false);

                if (response != null && response.has("items")) {
                    try {
                        JSONArray fir = response.getJSONArray("items");
                        List<JokeEntity> items = new ArrayList<JokeEntity>();
                        Gson gson = new Gson();
                        for (int i = 0; i < fir.length(); i++) {
                            String str = fir.getString(i);
                            JokeEntity j = gson.fromJson(str, JokeEntity.class);
                            items.add(j);
                        }
                        //将数据添加到适配器中
                        adapter.loadData(items);
                    } catch (JSONException e) {
                        e.printStackTrace();
                    } finally {

                    }
                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                error.printStackTrace();
            }
        });
        volleySingleton.addRequest(request);
    }


}
